package com.shadowvc.sdk.internal.util;

import com.shadowvc.sdk.Constants;
import com.shadowvc.sdk.exception.ApiException;
import com.shadowvc.sdk.internal.convert.ToJsonConverter;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 字符串字典结构
 * <p>
 * File: ApiHashMap.java
 * Description:
 * <p>
 * Copyright: Copyright (c) 2012 ecbox.com
 * Company: ECBOX,Inc.
 *
 * @author chenxiaochun
 * @version 1.0
 */
public class ApiHashMap extends HashMap<String, String> {

  private static final long serialVersionUID = -1277791390393392630L;

  public ApiHashMap() {
    super();
  }

  public ApiHashMap(Map<? extends String, ? extends String> m) {
    super(m);
  }

  public String put(String key, Object value) {
    String strValue = null;
    try {
      if (value == null) {
        strValue = null;
      } else if (value instanceof Date) {
        DateFormat format = new SimpleDateFormat(Constants.DATE_TIME_FORMAT);
        format.setTimeZone(TimeZone.getTimeZone(Constants.DATE_TIMEZONE));
        strValue = format.format((Date) value);
      } else if (value instanceof List) {
        Class<?> clazz = ((List<?>) value).get(0).getClass();
        strValue = new ToJsonConverter().toString((List<?>) value, clazz);
      } else if (value instanceof ApiObject) {
        strValue = new ToJsonConverter().toString(value);
      } else {
        strValue = value.toString();
      }
    } catch (ApiException e) {
      e.printStackTrace();
    }

    return this.put(key, strValue);
  }

  /**
   * 不允许null值
   *
   * @param key   键
   * @param value 值
   * @return 返回
   */
  public String put(String key, String value) {
    if (null != value) {
      return super.put(key, value);
    } else {
      return null;
    }
  }

}
